package cn.edu.fzu.homemaking.company.handler.impl;

import cn.edu.fzu.homemaking.company.api.UserApi;
import cn.edu.fzu.homemaking.company.cache.UserCache;
import cn.edu.fzu.homemaking.company.domain.entity.CompanyServer;
import cn.edu.fzu.homemaking.company.domain.entity.CompanyUser;
import cn.edu.fzu.homemaking.company.domain.entity.Demand;
import cn.edu.fzu.homemaking.company.domain.entity.Order;
import cn.edu.fzu.homemaking.company.handler.OrderError;
import cn.edu.fzu.homemaking.company.handler.OrderHandler;
import cn.edu.fzu.homemaking.company.handler.OrderSession;
import cn.edu.fzu.homemaking.company.service.CompanyServerService;
import cn.edu.fzu.homemaking.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component("orderUserPoolBuilderHandler")
public class OrderUserPoolBuilderHandler implements OrderHandler {

    private static final Logger  log = LoggerFactory.getLogger(OrderUserPoolBuilderHandler.class);

    @Resource
    private UserCache            userCache;

    @Resource
    private CompanyServerService companyServerService;

    @Resource
    private UserApi              userApi;

    @Override
    public boolean process(OrderSession session) {
        Order order = session.order;
        List<CompanyUser> companyUsers = null;

        if (order.getServerId() != null) {
            CompanyServer server = companyServerService.getById(order.getServerId());
            session.server = server;
            companyUsers = userCache.get(order.getCompanyId(), server.getLabelId());
        } else if (order.getDemandId() != null) {
            Demand demand = ResultUtil.parseValue(userApi.querySingleDemand(order.getDemandId()), Demand.class);
            if (demand == null) {
                session.error = OrderError.NO_DEMAND;
                return false;
            }
            session.demand = demand;
            companyUsers = userCache.get(order.getCompanyId(), demand.getLabelId());
        } else {
            session.error = OrderError.ORDER_ERROR;
            return false;
        }

        if (CollectionUtils.isEmpty(companyUsers)) {
            log.error("OrderUserPoolBuilderHandler error: no user");
            session.error = OrderError.NO_USER;
            return false;
        }

        session.companyUsers = new ArrayList<>(companyUsers);
        return true;
    }
}
